<!-- 更新 charts.vue，只保留产品价格范围饼图 -->
<template>
  <div class="charts-container">
    <h2>数据统计图表</h2>

    <!-- 饼图 - 产品价格范围分布 -->
    <div class="chart-card">
      <h3>产品售价范围分布</h3>
      <div ref="pieChartContainer" class="chart-wrapper"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import productApi from '../api/product_api.js'

const pieChartContainer = ref(null)
let pieChart = null

// 饼图配置 - 产品价格范围分布
const pieOption = {
  title: {
    text: '产品售价范围分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    top: 'bottom'
  },
  series: [
    {
      name: '售价范围',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 0, name: '¥0-100' },
        { value: 0, name: '¥100-300' },
        { value: 0, name: '¥300-500' },
        { value: 0, name: '¥500-1000' },
        { value: 0, name: '¥1000以上' }
      ]
    }
  ]
}

// 获取产品价格范围统计数据
const loadProductPriceRangeData = async () => {
  try {
    // 获取所有产品数据
    const response = await productApi.page({ current: 1, limit: 10000 })
    const products = response.data || []

    // 初始化价格范围统计
    const priceRangeCounts = {
      '¥0-100': 0,
      '¥100-300': 0,
      '¥300-500': 0,
      '¥500-1000': 0,
      '¥1000以上': 0
    }

    products.forEach(product => {
      // 使用 selling_price 字段而不是 price 字段
      const price = parseFloat(product.selling_price) || 0

      if (price >= 0 && price <= 100) {
        priceRangeCounts['¥0-100']++
      } else if (price > 100 && price <= 300) {
        priceRangeCounts['¥100-300']++
      } else if (price > 300 && price <= 500) {
        priceRangeCounts['¥300-500']++
      } else if (price > 500 && price <= 1000) {
        priceRangeCounts['¥500-1000']++
      } else if (price > 1000) {
        priceRangeCounts['¥1000以上']++
      }
    })

    // 计算总数用于百分比显示
    const totalCount = Object.values(priceRangeCounts).reduce((sum, count) => sum + count, 0)

    // 只显示有数据的价格区间
    const filteredData = Object.entries(priceRangeCounts)
        .filter(([name, value]) => value > 0)
        .map(([name, value]) => ({
          name,
          value
        }))

    // 更新饼图数据
    if (filteredData.length > 0) {
      pieOption.series[0].data = filteredData
    } else {
      // 如果没有数据，显示默认提示
      pieOption.series[0].data = [{ name: '暂无数据', value: 1 }]
    }

    if (pieChart) {
      pieChart.setOption(pieOption, true)
    }
  } catch (error) {
    console.error('加载产品价格范围数据失败:', error)

    // 错误处理：显示错误信息
    pieOption.series[0].data = [{ name: '数据加载失败', value: 1 }]
    if (pieChart) {
      pieChart.setOption(pieOption, true)
    }
  }
}

const initCharts = async () => {
  if (pieChartContainer.value) {
    pieChart = echarts.init(pieChartContainer.value)
    pieChart.setOption(pieOption)
  }

  // 加载图表数据
  await loadProductPriceRangeData()

  // 监听窗口大小变化，自适应图表
  window.addEventListener('resize', resizeCharts)
}

const resizeCharts = () => {
  if (pieChart) pieChart.resize()
}

onMounted(() => {
  initCharts()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)

  if (pieChart) pieChart.dispose()
})
</script>

<style scoped>
.charts-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.charts-container h2 {
  margin-bottom: 20px;
  color: #303133;
  text-align: center;
}

.chart-card {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-card h3 {
  margin-bottom: 15px;
  color: #606266;
  text-align: center;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}
</style>
